# -*- coding:utf-8 -*-
import os
import requests
import json
import base64
import time
import math
import hashlib
import argparse
import yaml
import uuid
import random


def parse_args():
    parser = argparse.ArgumentParser("集中化IT智能决策平台返回结果对比脚本")

    # 配置文件
    parser.add_argument('-c',
                        '--config',
                        type=str,
                        default='./configs/requests.yaml',
                        help='配置文件的路径')
    
    args = parser.parse_args()
    return args

# 适配推理网关协议的头部构造方法
def create_header(appID, appKey, Path, uuid_str, TDEV):
    appid = appID
    appKey = appKey
    uuid = "52a7bb1fc08841ad9efc76d8ae1ef07b"
    appName = Path.split('/')[1]

    for i in range(24 - len(appName)):
        appName += "0"
    capabilityname = appName
    # print(len(capabilityname))
    csid = appid + capabilityname + uuid
    tmp_xServerParam = {
        "appid": appid,
        "csid": csid
    }
    # print(tmp_xServerParam)
    xCurTime = str(int(math.floor(time.time())) + TDEV)
    # print(xCurTime)
    xServerParam = str(base64.b64encode(json.dumps(
        tmp_xServerParam).encode('utf-8')), encoding="utf8")
    # xServerParam = str(base64.b64encode(json.dumps(tmp_xServerParam).encode('utf-8')))

    # turn to bytes
    xCheckSum = hashlib.md5(
        bytes(appKey + xCurTime + xServerParam, encoding="utf8")).hexdigest()
    # xCheckSum = hashlib.md5(bytes(appKey + xCurTime + xServerParam)).hexdigest()

    header = {
        # "appKey": appKey,
        "X-Server-Param": xServerParam,
        "X-CurTime": xCurTime,
        "X-CheckSum": xCheckSum,
        # "content-type": "application/x-www-form-urlencoded"
        'Content-Type': 'application/json'
    }

    return header

def load_post_body(file_path):
    return {}

def process(url, path, TDEV, appid, appkey, body, output_dir):
    uid = str(uuid.uuid4())
    suid = ''.join(uid.split('-'))
    
    request_header = create_header(appid, appkey, path, suid, TDEV)
    output_name = str(body['index'])
    with open(body['body'], 'r') as f:
        request_body = json.load(f)
    f.close()

    # print()
    
    user_agent_list = ["Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
                    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
                    "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",]
        # print(random.choice(user_agent_list))
    user_agent = random.choice(user_agent_list)
        # print(user_agent)
    request_header['User-Agent'] = user_agent
    # request_header = {'Content-Type': 'application/json'} 

    request_failed = []
    try_num = 5
    while try_num > 0:
            try:
                result = requests.post(url+path, data=json.dumps(request_body), headers=request_header)
                try_num = 0
                if result.status_code != requests.codes.ok: # 请求成功但是服务器失败
                    # print(result.text.encode('utf-8').decode('unicode_escape'))
                    # return None, None
                    return False, (output_name, body['body'], "错误信息:"+str(result.status_code)+"-"+result.reason)
                    # return False, (output_name, body['body'], "错误信息:"+str(result.status_code)+"-"+result.text.encode('utf-8').decode('unicode_escape')['message'])
                response_data = json.loads(result.text.encode('utf-8').decode('unicode_escape'))
                with open(os.path.join(output_dir, output_name+".json"), 'w') as f:
                    json.dump(response_data, f, ensure_ascii=False, indent=4)
                return True, None
            except requests.exceptions.ConnectionError as ex:
                if try_num <= 0:
                    print("Failed to retrieve: " + url + path + "\n" + str(ex))
                    return False, (output_name, body['body'], "错误信息: 无法连接服务器")
                else:
                    print("{}-{}:连接失败，剩余尝试次数:{}".format(output_name, url+path, try_num))
                    try_num -= 1
                    time.sleep(0.5)
    

def main():
    args = parse_args()
    with open(args.config, 'r') as fc:
        config = yaml.load(fc, Loader=yaml.FullLoader)
    fc.close()

    # 创建保存结果的文件夹
    output_dir = config['output']
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    

    post_bodys = config['post_body']

    url, path, TDEV, appid, appkey = config['URL'], config['PATH'], config['TDEV'], config['APPID'], config['APPKey']
    print("-"*100)
    print("开发向统一AI平台发起测试请求...")
    for body in post_bodys:
        print("正在使用{}请求数据进行测试... ".format(body), end="")
        success, error  = process(url, path, TDEV, appid, appkey, body, output_dir)
        if not success:
            print('index:{}\tbody:{}\t{}'.format(error[0], error[1], error[2]))
        else:
            print("-- 请求成功")
    
    print("测试完成，测试结果储存与{}目录下".format(output_dir))
    print("-"*100)

if __name__ == "__main__":
    main()





# image_path = 'test1.jpg'
#
# with open(image_path, 'rb') as f:
#    base64_str = base64.b64encode(f.read())
#
#
# body = {
#			"requestTime": "2018-03-08 15:40:30",
#			"appId": " pdwsb_app ",
#			"image": base64_str
#	   }
# json_in = json.dumps(body, ensure_ascii=False)

# body = {
#     "name":"zhangsan"
# }
# # res = requests.post(url=URL+Path, data=json.dumps(body),headers=create_header())
# res = requests.post(url=URL + Path,data=body, headers=create_header())
# print("返回状态码：\t" + str(res.status_code))
# print("返回头部: \t", res.headers)
# print(res.text.encode('utf-8').decode('unicode_escape'))
